<template>
  <div ref="appContainer" class="app-container home-bg-padding">
    <CustomSearch
      ref="searchForm"
      show-all.sync="false"
      :show-switch-icon="false"
      @search="searchFn"
      @reset="resetFn"
    >
      <template #btns>
        <sec-button
          v-if="permissions(AddDept)"
          type="primary"
          icon="sec-icon-bianji"
          @click="addDepartment"
          >添加</sec-button
        >
        <sec-tooltip
          class="item"
          effect="dark"
          content="刷新"
          placement="top-start"
        >
          <sec-button
            icon="sec-icon-shuaxin"
            circle
            @click="getList"
          ></sec-button>
        </sec-tooltip>
      </template>
    </CustomSearch>
    <div class="query-table">
      <sec-table
        v-loading="loading"
        :data="department[0].children"
        size="mini"
        style="width: 100%; height: calc(100% - 42px); overflow-y: scroll"
        stripe
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        row-key="id"
      >
        <sec-table-column fixed prop="name" label="部门名称"></sec-table-column>
        <sec-table-column prop="weight" label="排序"></sec-table-column>
        <sec-table-column
          prop="createTime"
          label="创建时间"
          width="170"
        ></sec-table-column>
        <sec-table-column fixed="right" label="操作">
          <template slot-scope="scope">
            <sec-button
              v-if="permissions(AddDept)"
              type="text"
              size="small"
              icon="el-icon-plus"
              @click="localAddDepartment(scope.row)"
              >新增</sec-button
            >
            <sec-button
              v-if="permissions(EditDept)"
              type="text"
              size="small"
              icon="sec-icon-bianji"
              @click="localAddDepartment(scope.row, 'edit')"
              >修改</sec-button
            >
            <sec-button
              v-if="permissions(DeleteDept)"
              type="text"
              size="small"
              icon="el-icon-delete"
              @click="deleteOpen(scope.row)"
              >删除</sec-button
            >
          </template>
        </sec-table-column>
      </sec-table>
      <div class="pagination">
        <sec-pagination
          :current-page.sync="pagination.pageNo"
          :page-size="pagination.pageSize"
          layout="total,prev, pager, next,sizes"
          :total="pagination.totalCount"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        ></sec-pagination>
      </div>
    </div>
    <!-- 编辑弹框 -->
    <sec-dialog
      v-if="departmentVisible"
      :title="dialogTitle"
      :visible.sync="departmentVisible"
      :close-on-click-modal="false"
    >
      <sec-form ref="ruleForm" :model="form" :rules="rules">
        <sec-form-item
          label="上级部门"
          prop="parentNode"
          :label-width="formLabelWidth"
          class="demo-dynamic"
        >
          <sec-cascader
            v-model="form.parentNode"
            size="medium"
            clearable
            :options="department"
            :props="{ ...defaultProps, checkStrictly: true }"
            :show-all-levels="false"
            @change="selectChange"
          ></sec-cascader>
        </sec-form-item>
        <sec-form-item
          label="部门名称"
          :label-width="formLabelWidth"
          prop="departmentName"
        >
          <sec-input
            v-model="form.departmentName"
            size="medium"
            autocomplete="off"
            placeholder="请输入部门名称"
          ></sec-input>
        </sec-form-item>
        <sec-form-item label="排序" :label-width="formLabelWidth">
          <sec-input-number
            v-model="form.weight"
            size="medium"
            controls-position="right"
            :min="0"
            :max="1000"
          ></sec-input-number>
        </sec-form-item>
      </sec-form>
      <div slot="footer" class="dialog-footer">
        <sec-button
          icon="el-icon-circle-close"
          @click="departmentVisible = false"
          >取 消</sec-button
        >
        <sec-button type="primary" icon="el-icon-check" @click="confirm">
          确定
        </sec-button>
      </div>
    </sec-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { DeleteDept, AddDept, EditDept } from '@/const/permissions'
import http from '@/utils/http'
import pagination from '@/utils/mixins/pagination'
import { CustomSearch } from '@/components'
export default {
  name: 'AccessDepartment',
  components: {
    CustomSearch
  },
  mixins: [pagination],
  data: function () {
    return {
      DeleteDept,
      AddDept,
      EditDept,
      fn: 'addDepartment',
      dialogTitle: '新增',
      department: [{ children: [] }],
      departmentVisible: false,
      formLabelWidth: '120px',
      loading: false,
      selectDepartId: '',
      rules: {
        departmentName: {
          required: true,
          message: '请输入部门名称',
          trigger: 'blur'
        },
        parentNode: {
          type: 'array',
          required: true,
          message: '请选择上级部门',
          trigger: 'change'
        }
      },
      // order: 20,
      defaultProps: {
        children: 'children',
        label: 'name',
        value: 'id'
      },
      // parentNode: [],
      form: {
        parentNode: [],
        departmentName: '',
        weight: 1
      },
      tempNode: {}
    }
  },
  computed: {
    ...mapGetters(['permissions'])
  },
  created: function () {
    this.getList()
  },
  mounted: function () {
    // console.log(this.permissions)
  },
  methods: {
    getList() {
      this.loading = true
      http.getDepartment().then((res) => {
        // todo ****** 方便后面的数据处理，默认加一级根节点 *****
        const treeNode = [
          {
            children: res.data,
            createTime: '2018-01-22 19:00:23',
            id: '-1',
            isLock: false,
            name: '根部门',
            disabled: true,
            parentId: 99999999,
            weight: 1
          }
        ]

        /**
         * @description 建立节点引用关系方便后面的引用查找
         */
        const establishRef = (arr, parent) => {
          for (let i = 0; i < arr.length; i++) {
            const node = arr[i]
            parent && (node['parent'] = parent)
            if (Array.isArray(node.children)) {
              establishRef(node.children, node)
            }
          }
        }
        establishRef(treeNode)
        this.department = treeNode

        this.pagination.totalCount = res.data.length

        this.loading = false
      })
    },
    selectChange: function (aSelect) {
      this.form.parentNode = aSelect
    },
    localAddDepartment: function (node, command) {
      this.tempNode = node
      // 临时变量
      const { id } = node
      this.departmentVisible = true
      let found = false
      /**
       * @description 递归查找
       * *** 当前递归是深度优先遍历的策略.
       * *** 嵌套for循环遍历的跳出的确是一个小的问题，可以借助try catch之外就只能通过flag方式实现了
       */
      const recursionFindById = (arr, id) => {
        for (let i = 0; i < arr.length; i++) {
          const node = arr[i]
          if (node.id === id) {
            found = node
            break
          }
          if (Array.isArray(node.children) && !found) {
            recursionFindById(node.children, id)
          }
        }
      }

      recursionFindById(this.department, id)

      const idLink = [found.id]
      // 溯源id链
      const findParentId = (node) => {
        const parent = node.parent

        if (!parent) return

        idLink.unshift(parent.id)

        if (parent.id === id) {
          return
        } else {
          findParentId(parent)
        }
      }

      findParentId(found)

      if (command === 'edit') {
        this.dialogTitle = '修改'
        this.fn = 'updateDepartment'
        this.form.departmentName = node.name
        this.form.weight = node.weight
        idLink.pop()
      } else {
        this.form.departmentName = ''
        this.form.weight = 1
        this.dialogTitle = '新增'
        this.fn = 'addDepartment'
      }

      this.form.parentNode = idLink
    },
    addDepartment: function (user) {
      this.departmentVisible = true
      this.form.departmentName = ''
      this.form.weight = 1
      this.dialogTitle = '新增'
      this.fn = 'addDepartment'
    },
    filterNode(value, data) {
      if (!value) return true
      return data.name.indexOf(value) !== -1
    },
    currentChange(node, data) {
      console.log(node)
    },
    confirm: function () {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.departmentVisible = false
          console.log(
            ` [ confirm ] ----`,
            this.form.parentNode,
            this.form.departmentName
            // this.order
          )
          const param = {
            name: this.form.departmentName,
            parentId: this.form.parentNode[this.form.parentNode.length - 1],
            sortOrder: this.form.weight,
            weight: this.form.weight
          }
          if (this.fn === 'updateDepartment') {
            param['id'] = this.tempNode.id
            param['deptId'] = this.tempNode.id
          }

          http[this.fn](param).then((res) => {
            console.log(res)
            this.$message({
              type: 'success',
              message: `${this.dialogTitle}成功!`
            })
            this.getList()
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    deleteOpen(row) {
      console.log(row)
      this.$confirm(`是否确认删除名称为"${row.name}"的数据项? `, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        closeOnClickModal: false,
        type: 'warning'
      })
        .then(() => {
          http.deleteDepartment({ deptId: row.id }).then((res) => {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.getList()
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    }
  }
}
</script>

<style scoped lang="scss">
.line {
  padding: 10px 0;
  &.btn {
    padding-top: 0;
  }
  &.page {
    text-align: right;
  }
}
.query-table {
  padding: 8px;
  background: #fff;
  flex: 1;
  height: 1%;
  .operate {
    font-size: 12px;
  }
  .idot {
    width: 8px;
    height: 8px;
    background: #19be6b;
    border-radius: 50%;
    display: inline-block;
    margin-right: 5px;
  }
  .sec-icon-bangzhu1 {
    margin-left: 3px;
    color: rgb(45, 140, 240);
  }
  .pagination {
    text-align: right;
    padding-top: 8px;
    .el-pagination {
      padding-right: 0;
    }
    .el-pagination__sizes {
      margin: 0;
    }
    .el-pagination .el-pagination__sizes .el-select .el-input {
      margin-right: 0;
    }
  }
  .el-table {
    .el-table-column--selection {
      .cell {
        padding-left: 14px;
      }
    }
    .el-table__body {
      width: 100%;
      // 使表格兼容safari，不错位
      table-layout: fixed !important;
    }
  }
}
.item {
  width: 30px;
}
</style>
